package org.oslims.server.dao.hbm;

import java.util.List;

import org.hibernate.Query;
import org.oslims.domain.AbstractSample;
import org.oslims.domain.Analysis;
import org.oslims.domain.AnalysisResult;
import org.oslims.server.dao.AnalysisResultDao;

public class HbmAnalysisResultDao extends HbmGenericDao<AnalysisResult, Long> implements AnalysisResultDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<AnalysisResult> findBySample(AbstractSample abstractSample) {
		Query q = this.getSession().createQuery(
				"select distinct ar from AnalysisResult ar where ar.sample.id = :sampleId order by ar.analysis.doneIn.abbreviation, ar.analysis.name");
		q.setLong("sampleId", abstractSample.getId());

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AnalysisResult> findBySampleAndAnalysisAndState(AbstractSample abstractSample, Analysis analysis, String state) {
		Query q = this
				.getSession()
				.createQuery(
						"select distinct ar from AnalysisResult ar join fetch ar.parameterResults pr where ar.sample.id = :sampleId and ar.analysis.id = :analysisId and pr.state like :state");
		q.setLong("sampleId", abstractSample.getId());
		q.setLong("analysisId", analysis.getId());
		q.setString("state", state);

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AnalysisResult> findBySampleAndState(AbstractSample abstractSample, String state) {
		Query q = this.getSession().createQuery(
				"select distinct ar from AnalysisResult ar join fetch ar.parameterResults pr where ar.sample.id = :sampleId and ar.state like :state");
		q.setLong("sampleId", abstractSample.getId());
		q.setString("state", state);

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getAnalysisStatesForSample(String sampleCode) {
		Query q = this.getSession().createQuery("select distinct ar.state from AnalysisResult ar where ar.sample.code = :sampleCode)");
		q.setString("sampleCode", sampleCode);

		return q.list();
	}

}